#!/usr/bin/env node

const fs = require('fs');
const load = require('load-json-file');
const write = require('write-json-file');
const path = require('path');
const glob = require('glob');

// Update Typescript Repos
glob.sync(path.join(__dirname, '..', 'packages', 'turf-*', 'index.ts')).forEach(filepath => {
    const {dir} = path.parse(filepath);
    const pckgPath = path.join(dir, 'package.json');
    const pckg = load.sync(pckgPath);

    const formatedPckg = {
        name: pckg.name,
        version: updateVersion(pckg.version),
        description: pckg.description,
        main: 'index',
        types: 'index.d.ts',
        files: updateFiles(pckg.files),
        scripts: {
            'prepare': 'tsc',
            'pretest': 'tsc',
            'test': 'node test.js',
            'bench': 'node bench.js',
            'docs': 'node ../../scripts/generate-readmes'
        },
        repository: pckg.repository,
        keywords: pckg.keywords,
        author: pckg.author,
        contributors: pckg.contributors,
        license: pckg.license,
        bugs: pckg.bugs,
        homepage: pckg.homepage,
        devDependencies: updateDevDependencies(pckg),
        dependencies: pckg.dependencies
    };
    write.sync(pckgPath, formatedPckg, {indent: 2});

    // Remove extra files
    // To-Do

    // Add .gitignore
    fs.writeFileSync(path.join(dir, '.gitignore'), 'index.js');

    // Add Typescript configs
    if (false) {
        fs.writeFileSync(path.join(dir, 'tsconfig.json'), `{
    "compilerOptions": {
        /* Basic Options */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
        "declaration": true,                      /* Generates corresponding '.d.ts' file. */

        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */

        /* Module Resolution Options */
        "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    }
}`);

        fs.writeFileSync(path.join(dir, 'tslint.json'), `{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {},
    "rulesDirectory": []
}`);
    }
});

function entries(obj) {
    return Object.keys(obj || {}).map(key => [key, obj[key]]);
}

/**
 * @param {Array<string>} files Files
 * @returns {Array<string>} Files
 */
function updateFiles(files) {
    const newFiles = ['index.js', 'index.d.ts'];
    if (files.includes('lib')) newFiles.push('lib');
    return newFiles;
}

function updateDevDependencies(pckg) {
    const devDependencies = {};
    const dev = new Map(entries(pckg.devDependencies));
    dev.delete('rollup');
    dev.delete('@std/esm');
    dev
        .set('typescript', '*')
        .set('tslint', '*')
        .set('tape', '*')
        .set('@types/tape', '*')
        .set('benchmark', '*').forEach((version, name) => {
            devDependencies[name] = '*';
        });
    return devDependencies;
}

function updateVersion(version) {
    let [major, minor, patch] = version.split('.');
    patch = Number(patch) + 1;
    return `${major}.${minor}.${patch}`;
}
